#include "MyEventLoop.h"
#include "base/msleep.h"

MyEventLoop::MyEventLoop()
    :isLooping(false)
    ,isQuit(false)
{
    e = new SelectEvent();
}

MyEventLoop::~MyEventLoop()
{

}

void MyEventLoop::loop()
{
    isLooping = true;
    isQuit = false;

    while(!isQuit)
    {
        //std::cout << "----------Looping----------" << std::endl;
        //addToLoop();
        std::vector<MyHandler*> activeEvents;
        activeEvents.clear();
        // 调用epoll将活动的套接字描述符对应的Handler取出并处理
        e->Detect(activeEvents);

        if(activeEvents.empty())
        {
            Msleep(60);
        }

        for(std::vector<MyHandler*>::iterator iter = activeEvents.begin();
            iter != activeEvents.end(); ++iter)
        {
            std::cout << "----------Handle request----------" << std::endl;
            // 处理客户端请求的入口
            (*iter)->handle();
            e->removeFd((*iter)->connFd());
            delete *iter;
        }

        activeEvents.clear();
    }
    isLooping = false;

}
void MyEventLoop::quit()
{
     isQuit = true;
}
void MyEventLoop::addToLoop(const int fd)
{
    e->addToEvent(fd);
}

void MyEventLoop::addToLoop()
{

}
